<?php

namespace app\admin\model;

use think\Model;
use app\admin\model\wallet\Record;
use app\admin\model\wallet\Log;
use think\Db;
use app\common\model\Back;

class Wallet extends Model
{



    // 表名
    protected $name = 'wallet';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = false;
    protected $multiples  = 1;

    // 追加属性
    protected $append = [
        'back_tag_name'
    ];

    public function user()
    {
        return $this->belongsTo('User','user_id','id',[],'left')->setEagerlyType(0);
    }

    //关联银行
    public function getBackTagNameAttr($value,$data)
    {
        switch ($data['back_tag']){
            case 'ICBC':
                return '中国工商银行';
                break;
            case 'CMBC':
                return '招商银行';
                break;
            case 'ABC':
                return '中国农业银行';
                break;
            case 'CBC':
                return '中国建设银行';
                break;
            case 'BC':
                return '中国银行';
                break;
            case 'CMSC':
                return '中国民生银行';
                break;
            case 'CEB':
                return '中国光大银行';
                break;
            case 'CITIC':
                return '中信银行';
                break;
            case 'CTB':
                return '交通银行';
                break;
            case 'CIB':
                return '兴业银行';
                break;
            case 'SPDB':
                return '上海浦东发展银行';
                break;
            case 'PBC':
                return '中国人民银行';
                break;
            case 'HXB':
                return '华夏行';
                break;
            case 'PSBC':
                return '中国邮政储蓄银行';
                break;
            case 'OTHER':
                return '其他银行';
                break;
        }
        //return $this->hasOne('app\common\model\Back','tag','back_tag')->setEagerlyType(0);;
    }

    public function downScore($data,$operation)
    {
        $wallet = $this->find($data['id']);

        if( $wallet['money'] < $data['money'] ){
            return ['code'=>0,'msg'=>'金额输入有误','data'=>[]];
        }
        $record_sn = checkRecordSn();
        Db::startTrans();//开启事物
        try{
            $wallet->money = $wallet['money'] - $data['money'];
            $wallet->save();

            $record = new Record;
            $log = new Log;
            $recordData = [
                'record_sn' => $record_sn,
                'user_id'   => $wallet['user_id'],
                'type'      => 9,
                'money'     => $data['money'],
                'remark'    => $data['remarks'],
                'pay_status'=> 1,//支付成功
                'pay_time'  => time(),
                'site'          => $wallet['site'],
                'operation' => $operation
            ];
            $record->data($recordData)->save();
            $logData = [
                'record_sn'     => $recordData['record_sn'],
                'user_id'       => $wallet['user_id'],
                'change_money'  => '-' . $data['money'],
                'money'         => $wallet['money'],//变动后的金额
                'remark'        => $data['remarks'],
                'site'          => $wallet['site']
            ];
            $log->data($logData)->save();
            Db::commit();
            return ['code'=>200,'msg'=>'成功','data'=>[]];
        }catch (Exception $e)
        {
            file_put_contents(
                WALLET_ERROR_PATH,
                '【' . date( 'Y-m-d H:i:s', $_SERVER[ 'REQUEST_TIME' ] ) . '】  下分异常：'.json_encode($e). PHP_EOL,
                FILE_APPEND
            );
            Db::rollback();
            return ['code'=>0,'msg'=>'失败','data'=>$e];
        }

    }

    public function upScore($data,$operation)
    {
        $record_sn = checkRecordSn();
        Db::startTrans();//开启事物
        try {
            Db::name('wallet')->where('id', '=', $data['id'])->update([
                'money' => Db::raw('money+' . $data['money'])
            ]);
            $wallet = $this->find($data['id']);
            $recordData = [
                'record_sn'     => $record_sn,
                'user_id'       => $wallet['user_id'],
                'type'          => $data['type'],//1微信充值.2支付宝.3银联
                'money'         => $data['money'],
                'remark'        => $data['remarks'],
                'pay_status'    => 1,//支付成功
                'pay_time'      => time(),
                'site'          => $wallet['site'],
                'operation' => $operation
            ];
            $logData = [
                'record_sn'     => $record_sn,
                'user_id'       => $wallet['user_id'],
                'change_money'  => '+' . $data['money'],
                'money'         => $wallet['money'],//变动后的金额
                'remark'        => $data['remarks'],
                'site'          => $wallet['site'],
                'beallwate'     => $data['money'] * $this->multiples,
                'surpluswate'   => $data['money'] * $this->multiples,
                'multiples'     => $this->multiples,
            ];

            $record = new Record;
            $log = new Log;
            $record->data($recordData)->save();
            $log->data($logData)->save();

            $waterMultiple = new WaterMultiple();
            $water = $waterMultiple::where('user_id',$wallet['user_id'])

                //->where('surpluswate','>',0)
                ->order('id','desc')->limit(1)->field('surpluswate,beallwate')->find();
            //1.获取上一条记录，上一条记录surpluswate>0  是赠送||充值上分||未达标流水
            //2.上一条记录surpluswate<=0
            //1:剩余未结流水(surpluswate)=充值*流水倍数 + surpluswate(剩余未结流水)；需要总流水(beallwate)=充值*流水倍数
            //2:重置剩余未结流水->剩余未结流水(surpluswate)=充值*流水倍数;需要总流水(beallwate)=充值*流水倍数

            if( $water && $water['surpluswate'] > 0 ){
                $surpluswate = $data['money'] * $this->multiples + $water['surpluswate'];
                if( $water['surpluswate'] > 0 ){
                    $beallwate = $data['money'] * $this->multiples + $water['beallwate'];
                }else{
                    $beallwate = $data['money'] * $this->multiples;
                }
            }else{
                $surpluswate = $data['money'] * $this->multiples;
                $beallwate = $data['money'] * $this->multiples;
            }

            $waterMultipleData = [
                'remark'    => $data['remarks'],
                'record_sn' => $record_sn,
                'multiples' => $this->multiples,
                'change_money' => $data['money'],
                'beallwate' => $beallwate,
                'surpluswate'=> $surpluswate,
                'user_id'   => $wallet['user_id'],
                'type'      => $data['type']
            ];
            $waterMultiple->data($waterMultipleData)->save();

            Db::commit();
            return ['code'=>200,'msg'=>'成功','data'=>[]];
            //Record::insert($recordData);
        }catch (Exception $e)
        {
            file_put_contents(
                WALLET_ERROR_PATH,
                '【' . date( 'Y-m-d H:i:s', $_SERVER[ 'REQUEST_TIME' ] ) . '】  上分异常：'.json_encode($e). PHP_EOL,
                FILE_APPEND
            );
            Db::rollback();
            return ['code'=>0,'msg'=>'失败','data'=>$e];
        }
    }


    public function giveScore($data,$operation)
    {
        $record_sn = checkRecordSn();
        Db::startTrans();//开启事物
        try {
            $this->where('id', '=', $data['id'])->update([
                'money' => Db::raw('money+' . $data['money'])
            ]);
            $wallet = $this->find($data['id']);
            $recordData = [
                'record_sn'     => $record_sn,
                'user_id'       => $wallet['user_id'],
                'type'          => 5,//赠送
                'money'         => $data['money'],
                'remark'        => $data['remarks'],
                'pay_status'    => 1,//支付成功
                'pay_time'      => time(),
                'site'          => $wallet['site'],
                'operation'     => $operation,
            ];

            $logData = [
                'record_sn'     => $record_sn,
                'user_id'       => $wallet['user_id'],
                'change_money'  => '+' . $data['money'],
                'money'         => $wallet['money'],//变动后的金额
                'remark'        => $data['remarks'],
                'site'          => $wallet['site'],
                'beallwate'     => $data['money'] * $data['multiples'],
                'surpluswate'   => $data['money'] * $data['multiples'],
                'multiples'     => $data['multiples'],
            ];
            $record = new Record;
            $log = new Log;
            $record->data($recordData)->save();
            $log->data($logData)->save();

            $waterMultiple = new WaterMultiple();

            $water = $waterMultiple::where('user_id',$wallet['user_id'])
                //->where('surpluswate','>',0)
                ->order('id','desc')->limit(1)->field('surpluswate,beallwate')->find();
//            $surplusum = $water ? $water['surpluswate'] : 0;
//            $beallwate = $water ? $water['beallwate'] : 0;
            if( $water && $water['surpluswate'] > 0 ){
                $surpluswate = $data['money'] * $data['multiples'] + $water['surpluswate'];
                if( $water['surpluswate'] > 0 ){
                    $beallwate = $data['money'] * $data['multiples'] + $water['beallwate'];
                }else{
                    $beallwate = $data['money'] * $data['multiples'];
                }
            }else{
                $surpluswate = $data['money'] * $data['multiples'];
                $beallwate = $data['money'] * $data['multiples'];
            }

            $waterMultipleData = [
                'remark'    => $data['remarks'],
                'record_sn' => $record_sn,
                'multiples' => $data['multiples'],
                'change_money' => $data['money'],
                'beallwate' => $beallwate,
                'surpluswate'=> $surpluswate,
                'user_id'   => $wallet['user_id'],
                'type'      => 5
            ];

            $waterMultiple->data($waterMultipleData)->save();
            Db::commit();
            return ['code'=>200,'msg'=>'成功','data'=>[]];
            //Record::insert($recordData);
        }catch (Exception $e)
        {
            file_put_contents(
                WALLET_ERROR_PATH,
                '【' . date( 'Y-m-d H:i:s', $_SERVER[ 'REQUEST_TIME' ] ) . '】  赠送异常：'.json_encode($e). PHP_EOL,
                FILE_APPEND
            );
            Db::rollback();
            return ['code'=>0,'msg'=>'失败','data'=>$e];
        }
    }

}
